<?php

class Auth {
  /**
   * invalid indentity
   */
  const INVALID_IDENTITY = -1;

  /**
   * 
   */
  const INVALID_CREDENTIAL = -2;

  /**
   * test if email, password pair exists in account system.
   * return unsigned int if true, or return nagative int if failed.
   * @param string $email
   * @param string $password
   * @return int 
   */
  public static function test($email, $password) {
    $db = db::factory();
    $table = db::get_tablename('user');
    $row = $db->fetchRow("select * from $table where email=?", $email);

    print_r($row);

    if (!$row) {
      return self::INVALID_IDENTITY;
    }
    if (self::build_password($password, $row['password_salt']) == $row['password']) {
      return $row['id'];
    }
    return self::INVALID_CREDENTIAL;
  }

  public static function login($user_id, $remember = false) {
    $_SESSION['user_id'] = $user_id;
    if ($remember) {
      self::remember($user_id);
    }
  }

  public static function logout() {
    self::clean();
    $name = setting::get('user.cookie_name');
    $_SESSION['user_id'] = 0;
    if ($value = @$_COOKIE[$name]) {
      @setcookie($key, '', 1);
    }
  }

  /**
   * remember this user to automatic login
   * @param int $user_id
   */
  public static function remember($user_id) {

    self::clean();

    $name = setting::get('user.cookie_name');
    $value = common::get_random_string(32);
    $expire_time = time() + (int) setting::get('user.remember_time');

    if (@setcookie($name, $value, $expire_time)) {
      $data = array(
          'id' => $value,
          'user_id' => $user_id,
          'expire_time' => $expire_time,
      );
      db::factory()->insert(db::get_tablename('user_remember'), $data);
    }
  }

  /**
   * remove this user from remember authenticate, it's usually invoked by logout
   */
  public static function clean() {
    $name = setting::get('user.cookie_name');
    if ($value = @$_COOKIE[$name]) {
      @setcookie($name, '', 1);
      $table = db::get_tablename('user_remember');
      db::factory()->query("delete from $table where id=?", $value);
    }
  }

  /**
   * 
   */
  public static function get_current_id() {
    if ($user_id = @$_SESSION['user_id']) {
      return $user_id;
    }
    $name = setting::get('user.cookie_name');
    if ($value = @$_COOKIE[$name]) {
      $table = db::get_tablename('core_user_remember');

      $sql = "select * from $table where id='$id'";

      $row = db::factory()->fetchRow($sql);

      if ($row && $row['expire_time'] > time()) {

        $_SESSION['user_id'] = $row['user_id'];
        
        return $row['user_id'];
      } else {

        @setcookie($key, '', 1);
      }
    }
    return 0;
  }

  /**
   *
   * @param  string $input_password
   * @param  string $password_salt
   * @return string
   */
  public static function build_password($input_password, $password_salt) {
    return sha1($input_password . $password_salt, false);
  }
}

session::start();